/*  Copyright (C) 2011  Google Inc.
 *  Copyright (C) 2011  social-tourist.org
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.socialtourist.web.server;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.socialtourist.web.shared.data.Image;

/**
 * This class is an adaption of an example found on the appengine docs.
 * @see http://code.google.com/intl/it-IT/appengine/articles/java/serving_dynamic_images.html
 */
public class GetImageServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String title = req.getParameter("id");
		if (title == null)
			return;
		Image image = getImage(title);

		if (image != null && image.getImageType() != null
				&& image.getImage() != null) {
			// Set the appropriate Content-Type header and write the raw bytes
			// to the response's output stream
			resp.setContentType(image.getImageType());
			resp.getOutputStream().write(image.getImage());
		} else {
			// FIXME default image.
			//resp.sendRedirect("/static/noimage.jpg");
		}
	}

	// ...

	/**
	 * Queries the datastore for the Movie object with the passed-in title. If
	 * found, returns the Movie object; otherwise, returns null.
	 * 
	 * @param title
	 *            movie title to look up
	 */
	private Image getImage(String ids) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Long id = Long.parseLong(ids);
		
		// Search for any Movie object with the passed-in title; limit the
		// number
		// of results returned to 1 since there should be at most one movie with
		// a given title

		try{
			Image image = pm.getObjectById(Image.class, id);
			return image;
			
		} finally {
			pm.close();
		}
	}
}